package lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author fei
 * @date 2023/1/8 17:12
 * @description 可重入锁，显式锁
 */
public class ReEntryLockDemo2 {

    static Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "\t ---- come in 外层调用");
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + "\t ---- come in 内层调用");
                } finally {
                    lock.unlock();
                }
            } finally {
                // 这里故意注释，实现加锁次数和释放次数不一样
                // 由于加锁次数 和 释放次数不一样，第二个线程始终无法获取到锁，导致一直在等待
                // 正常情况，加锁几次就要解锁几次
                // lock.unlock();
            }
        }, "t1").start();


        new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "\t ----- come in 外层调用");
            } finally {
                lock.unlock();
            }
        }, "t2").start();
    }

}
